package com.shiro_demo;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

/**
 * @author liang
 */
public class CustomRealm extends AuthorizingRealm {

    /**
     * 此处实现授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取到用户名
        String username = (String) SecurityUtils.getSubject().getPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> set = new HashSet<>();
        set.add("user:admin");
        set.add("user:show");
        info.setStringPermissions(set);

        return info;
    }

    /**
     * 此处实现认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //取出输入的用户名和密码
        String username = (String) authenticationToken.getPrincipal();
        String userpwd = new String((char[]) authenticationToken.getCredentials()) ;
        //假设是从数据库中根据username查出的密码
        String pwd = "123123";
        //进行判断
        if(username == null){ // 假设没有查到用户
            throw new AccountException("用户不存在");
        }
        //密码的话会自动判断
        return new SimpleAuthenticationInfo(username,pwd,ByteSource.Util.bytes(username + "salt"),getName());
    }
    public String md5Pwd(String username, String password){
        String md5Pwd = new SimpleHash("MD5", password,
                ByteSource.Util.bytes(username + "salt"), 2).toHex();
        return md5Pwd;
    }
}
